#include "headers_cpp.h"
#include "lsp_client.h"

#include <stdio.h>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <string>

// If we want to allow the caller to specify the destination
void SeperateInput(const char *, char *, char *);

using namespace std;

int main(int argc, char** argv) 
{
	srand(12345);
	if(argc != 4)
	{
		cout << "Not proper agruments." << endl;
		return 0;
	}

	//Parse Arguments
	string hostport = argv[1];
	int indexofcol = hostport.find_first_of(":",0);
	if(indexofcol == string::npos)
	{
		cout << "Not proper agruments." << endl;
		return 0;
	}
	string dest = hostport.substr(0,indexofcol);
	string port = hostport.substr(indexofcol+1,hostport.size()-indexofcol-1);

	//cout << "dest: " << dest << endl << "port: " << port << endl;

	lsp_client* lsp = lsp_client_create(dest.c_str(), atoi(port.c_str()));

	// Check connection
	if(lsp == NULL)
	{
		printf("Server connection failed.");
		return -1;
	}

	//Prepare lower and upper
	string lower = "";
	string upper = "";
	int num = atoi(argv[3]);
	if(num < 1 || num > 7)
	{
		cout << "Not proper agruments." << endl;
		return 0;
	}
	for(int k = 0; k<num; ++k)
	{
		lower.push_back('a');
		upper.push_back('z');
	}


	//Prepare Payload
	ostringstream oss;
	oss << "c " << argv[2] << " " << lower << " " << upper;
	string to_send = string(oss.str());

	// Write hash and length
	if(!lsp_client_write(lsp, (uint8_t*) to_send.c_str(), to_send.length()+1))
	{
		cout << "Server write failed." << endl;
		lsp_client_close(lsp);
		return -1;
	}

	char* pld; pld = (char*) malloc(1024);
	int lth = lsp_client_read(lsp, (uint8_t*) pld);

	// Print result
	if(lth <= 0)
	{
		cout << "Disconnected" << endl;
	}
	else
	{
		string read = string(pld);
		bool found = (read[0] == 'f');
		if(found)
		{
			string pass = read.substr(2,read.length()-2);
			cout << "Found: " << pass << endl;
		}
		else
		{
			cout << "Not Found" << endl;
		}
	}

	//lsp_client_close(lsp);
	return 0;
}
